import React, { useState, useEffect } from 'react';
import { useObservable } from 'rxjs-hooks';
import * as echarts from 'echarts';
import { filter, tap } from 'rxjs';
import { isEmpty, merge } from 'lodash';
import defaultOption from './config';

import useResize from '../../../Hooks/useResize';

import { ChartOptions, RSEChartProps } from './interface';

export default ({ option, ...props }: RSEChartProps) => {
  const [echart, setEChart] = useState<echarts.ECharts | null>(null);
  const [element, { width, height }] = useResize<HTMLDivElement>({
    width: props.width,
    height: props.height,
  });

  // 初始化echarts
  useEffect(() => {
    const echart = echarts.init(element.current as HTMLDivElement);
    setEChart(echart);

    return () => {
      echart.dispose();
    };
  }, []);

  // setOptions
  useObservable<any, [echarts.ECharts | null, ChartOptions]>(
    (state$, inputs$) =>
      inputs$.pipe(
        filter(([echart, option]) => !isEmpty(echart) && !isEmpty(option)),
        tap(([echart, option]) => {
          echart?.setOption(merge(defaultOption, option) as echarts.EChartsCoreOption)
        })
      ),
    null,
    [echart, option],
  );

  // 父级元素变化 重新resize
  useEffect(() => {
    if (echart) {
      echart.resize();
    }
  }, [echart, width, height]);

  return <div ref={element} style={{ width: '100%', height: '100%' }}></div>;
};
